package cpm.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import cpm.atguigu.gulimall.seckill.feign.CouponFeignService;
import cpm.atguigu.gulimall.seckill.feign.ProductFeignService;
import cpm.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import cpm.atguigu.gulimall.seckill.service.SeckillService;
import cpm.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import cpm.atguigu.gulimall.seckill.vo.SeckillSessionsWithSkusVo;
import cpm.atguigu.gulimall.seckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    ProductFeignService productFeignService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    CouponFeignService couponFeignService;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKUKILL_STOCK_SEMAPHORE = "seckill:stock:";   //后面接的就是商品的随机码
    /**
     *
     * 实现秒杀商品的上架
     *  1）去数据库扫描，看哪些活动需要参与秒杀
     */
    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1）去数据库扫描，看哪些活动需要参与秒杀以及对应有哪些商品
        //我们去要查看优惠服务
        R r = couponFeignService.getLatest3DaySession();
        if(r.getCode() == 0){
            List<SeckillSessionsWithSkusVo> data = r.getData("data", new TypeReference<List<SeckillSessionsWithSkusVo>>() {
            });
            //2）上架商品，即将商品数据放入redis中
            //我们在redis中存入两类信息
            //2.1缓存活动信息以及对应的所有商品SkuId    list结构
            saveSessionInfos(data);
            //2.2缓存活动的关联商品的详细信息          hash结构
            saveSessionSkuInfo(data);
        }
    }

    /**
     * 获取当前可以参与秒杀的商品信息
     * @return
     */
    @Override
    public List<SeckillSkuRedisTo> getCuuentSeckillSkus() {
        //1.确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();
        Set<String> keys = stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        //返回所有当前时间所属的秒杀场次的id,但只会有一个秒杀场次
        List<String> collect = keys.stream().filter((item) -> {
            int i = item.lastIndexOf(":");
            String sessionTime = item.substring(i + 1);
            String[] s = sessionTime.split("_");
            Long start = Long.parseLong(s[0]);
            Long end = Long.parseLong(s[1]);
            return time >= start && time <= end;
        }).collect(Collectors.toList());
        //只有一个秒杀场次，集合里面页只有一个元素，取出来就好
        String key = collect.get(0);
        //从秒杀场次中获取所有的商品信息，展示到页面上
        List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        List<String> list = hashOps.multiGet(range);
        if(list != null && list.size() > 0){
            List<SeckillSkuRedisTo> collect1 = list.stream().map((item) -> {
                SeckillSkuRedisTo skuRedisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
                return skuRedisTo;
            }).collect(Collectors.toList());
            return collect1;
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = LoginUserInterceptor.local.get();
        //1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = hashOps.get(killId);
        if(StringUtils.isEmpty(s)){
            return null;
        }else {
            SeckillSkuRedisTo skuRedisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
            //2.校验合法性
            //a）当前时间是否超过了秒杀活动、b）验证随机码和商品id是否和redis中的一样 c）验证购买数量是否在每个人的限购数量之内 d）保证幂等性(即这个人是否已经购买过,只需要给redis中添加标志位数据即可)
            //a）
            Long startTime = skuRedisTo.getStartTime();
            Long endTime = skuRedisTo.getEndTime();
            long time = new Date().getTime();
            if(time>=startTime && time<=endTime){
                //b）
                String randomCode = skuRedisTo.getRandomCode();
                Long skuId = skuRedisTo.getSkuId();
                if(randomCode.equals(key) && skuId.toString().equals(killId.substring(killId.indexOf("_")+1))){
                    //c）
                    if(num <= skuRedisTo.getSeckillLimit()){
                        //d）只要执行了秒杀就在redis中占一个位: userId_SessionId_skuId
                        String redisKey = memberRespVo.getId()+"_"+skuRedisTo.getPromotionId()+"_"+skuId;
                        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), endTime - startTime, TimeUnit.MILLISECONDS);
                        if(aBoolean){
                            //占位成功说明从来没有秒杀过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKUKILL_STOCK_SEMAPHORE + skuRedisTo.getRandomCode());
                            try {
                                boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                //秒杀成功
                                //快速下单，给Mq发送消息。生成订单号并返回
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                //seckillOrderTo.setxxxxx
                                rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrderTo);
                                return timeId;
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }else {
                            //说明已经买过了
                            return null;
                        }
                    }
                }else {
                    return null;
                }
            }else {
                return null;
            }
        }
        return null;
    }

    /**
     * 缓存活动信息以及对应的所有商品SkuId    list结构
     */
    private void saveSessionInfos(List<SeckillSessionsWithSkusVo> data){
        data.stream().forEach((item)->{
            long start = item.getStartTime().getTime();
            long end = item.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX+start+"_"+end;
            //幂等性判断
            Boolean hasKey = stringRedisTemplate.hasKey(key);
            if(!hasKey){
                List<String> collect = item.getRelationSkus().stream().map(seckillSkuVo -> seckillSkuVo.getPromotionId()+"_"+seckillSkuVo.getSkuId().toString()).collect(Collectors.toList());
                stringRedisTemplate.opsForList().leftPushAll(key,collect);
            }

        });
    }

    /**
     * 缓存活动的关联商品的详细信息
     * @param data
     */
    private void saveSessionSkuInfo(List<SeckillSessionsWithSkusVo> data){
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        data.stream().forEach((item) ->{
            item.getRelationSkus().stream().forEach((seckillSkuVo)->{

                String code = UUID.randomUUID().toString().replace("-", "");

                //幂等性判断
                if(!stringRedisTemplate.hasKey(seckillSkuVo.getPromotionId()+"_"+seckillSkuVo.getSkuId().toString())){
                    SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
                    //1.sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,seckillSkuRedisTo);
                    //2.sku的基本数据
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if(skuInfo.getCode() == 0){
                        SkuInfoVo skuInfoVo = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        seckillSkuRedisTo.setSkuInfoVo(skuInfoVo);
                    }
                    //3.保存秒杀的开始结束时间。
                    seckillSkuRedisTo.setStartTime(item.getStartTime().getTime());
                    seckillSkuRedisTo.setEndTime(item.getEndTime().getTime());
                    //4.保存商品的随机码  seckill?skuId=1&key=sacfaDFSA

                    seckillSkuRedisTo.setRandomCode(code);

                    String jsonString = JSON.toJSONString(seckillSkuRedisTo);
                    hashOps.put(seckillSkuVo.getPromotionId()+"_"+seckillSkuVo.getSkuId().toString(),jsonString);

                    //幂等性保证。信号量如果重复设置那就起不到限流的作用
                    //5.为秒杀商品设置信号量。使用库存(即可以秒杀的数量)作为分布式信号量
                    //这样的话，请求一进来，先获取秒杀商品的信号量，获取到了，信号量减一，获取不到，请求就被挡在了外面，根本到不了数据库
                    //信号量最大的作用就是限流，只限定有限的流量进来。没有进来的请求都不能执行业务逻辑
                    RSemaphore semaphore = redissonClient.getSemaphore(SKUKILL_STOCK_SEMAPHORE + code);
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
                }






            });
        });
    }

}
